<template>
  <window :softID="softID">
    <template v-slot:contain>
      <div class="content">
        <div class="diskmenu">
          <div class="top"></div>
          <div class="bottom">
            <div class="item">
              <div class="text">个人收藏</div>
              <div class="text" @click="getFileData({ id: 1 })">
                <img src="http://localhost:5001/desktop.png" alt="" />
                <div>桌面</div>
              </div>
              <div class="text">
                <img src="http://localhost:5001/delivery.png" alt="" />
                <div>隔空投送</div>
              </div>
              <div class="text">
                <img src="http://localhost:5001/lastest.png" alt="" />
                <div>最近使用</div>
              </div>
              <div class="text">
                <img src="http://localhost:5001/applicationmini.png" alt="" />
                <div>应用程序</div>
              </div>
              <div class="text">
                <img src="http://localhost:5001/download.png" alt="" />
                <div>下载</div>
              </div>
            </div>
            <div class="item">
              <div class="text">标签</div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">红色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">橙色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">黄色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">绿色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">蓝色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">紫色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">灰色</div>
              </div>
              <div class="text">
                <div class="bot"></div>
                <div class="text">所有标签</div>
              </div>
            </div>
          </div>
        </div>
        <div class="maincontent">
          <div class="top">
            <div class="left">
              <div class="preFile" @click="preFile">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-left-outlined"></use>
                </svg>
              </div>
              <div class="nextFile" @click="nextFile">
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-right-outlined"></use>
                </svg>
              </div>
              <div class="curName">{{ curfileInfo.docName }}</div>
            </div>
            <div class="right"></div>
          </div>
          <div class="center">
            <div class="left">
              <div class="head">
                <div class="temp">
                  <div class="name">名称</div>
                  <div class="memorysize">大小</div>
                  <div class="catagory">种类</div>
                  <div class="createdate">添加日期</div>
                </div>
              </div>
              <div class="filecontain">
                <ContextMenuDoc ref="contextmenu"></ContextMenuDoc>
                <div
                  class="filebar"
                  v-for="filebar in filebarArr"
                  :key="filebar.createAt"
                  @dblclick="fileOpen(filebar)"
                  @contextmenu="handleRightClick(filebar, $event)"
                >
                  <div class="filename">
                    <img :src="filebar.src" alt="" />
                    <div v-if="!filebar.Renameing">
                      {{ filebar.name }}
                    </div>
                    <div v-else>
                      <input
                        type="text"
                        ref="input"
                        @keyup.enter="renameItem"
                      />
                    </div>
                  </div>
                  <div class="memorysize">{{ filebar.size }}</div>
                  <div class="filelkind">{{ filebar.kind }}</div>
                  <div class="createtime">{{ filebar.createTime }}</div>
                </div>
              </div>
            </div>
            <div class="right"></div>
          </div>
          <div class="bottom">
            <div class="path">
              <div
                class="item"
                v-for="(item, index) in curPathArr"
                :key="index"
                @click="getFileData(curPathArr[index])"
              >
                <img src="http://localhost:5001/file.png" alt="" />
                <span>{{ item.fatherName }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </window>
</template>

<script>
import ContextMenuDoc from "../MacComponents/contextMenuDocument.vue";
export default {
  components: {
    ContextMenuDoc,
  },
  props: ["softID"],
  name: "FileExplore",
  data() {
    return {
      curfileInfo: {
        id: 1,
      },
      filebarArr: [],
      curPath: [],
      filetextArr: [],
      filebarchoosed: null,
      forceActive: null,
      nowActive: null,
      ClickClearMenu: null,
      renameEvent: null,
      isRenameing: false,
      curPathArr: [],
      preFileInfo: {},
      nextFileInfo: {},
    };
  },
  async mounted() {
    this.bus.$on("getFileData", this.getFileData);
    this.bus.$on("fileContextController", this.fileContextController);
    await this.getFileData(this.curfileInfo);
  },
  methods: {
    preFile() {
      localStorage.setItem("preFileInfo", JSON.stringify(this.curfileInfo));
      this.getFileData(this.curPathArr[this.curPathArr.length - 2]);
    },
    nextFile() {
      this.preFileInfo = JSON.parse(localStorage.getItem("preFileInfo"));
      localStorage.removeItem("preFileInfo");
      if (this.preFileInfo) {
        this.getFileData(this.preFileInfo);
      }
    },
    onInit() {
      const filebar = this.$el.querySelectorAll(".filebar");
      if (filebar.length == 0) return;
      filebar.forEach((item, index) => {
        item.addEventListener("click", () => {
          if (this.forceActive) this.forceActive.classList.remove("active");
          this.forceActive = item;
          this.forceActive.classList.add("active");
        });
      });
    },
    handleRightClick(fileinfo, event) {
      // 右键显示菜单
      this.filebarchoosed = fileinfo;
      this.showContextmenu(event);
    },
    async fileContextController(id) {
      // 菜单消失
      this.$refs.contextmenu.$el.style.display = "none";
      switch (id) {
        case 0:
          //  打开
          break;
        case 1:
          // 移动到废纸篓
          this.removeFile();
          break;
        case 2:
          break;
        case 3:
          // 重命名事件
          // 将选中文件设置为重命名状态;
          if (this.filebarchoosed.iconUrl !== "txt.png") {
            console.log(this.filebarchoosed);
            this.$set(this.filebarchoosed, "Renameing", true);
            this.$nextTick(() => {
              this.renameEvent = this.$refs.input[0].addEventListener(
                "blur",
                () => {
                  this.$refs.input[0].removeEventListener(
                    "blur",
                    this.renameEvent
                  );
                  this.renameItem();
                }
              );
              this.$refs.input[0].value = this.filebarchoosed.name;
              this.$refs.input[0].focus();
            });
          } else {
            this.$set(this.filebarchoosed, "Renameing", true);
            this.$nextTick(() => {
              this.renameEvent = this.$refs.input[0].addEventListener(
                "blur",
                () => {
                  this.$refs.input[0].removeEventListener(
                    "blur",
                    this.renameEvent
                  );
                  this.renameItem();
                }
              );
              this.$refs.input[0].value = this.filebarchoosed.name;
              this.$refs.input[0].focus();
            });
          }

          break;
        case 4:
          break;
        case 5:
          break;
        default:
          break;
      }
    },
    async removeFile() {
      if (this.filebarchoosed.iconUrl != "txt.png") {
        const res = await this.http.post(
          `document/${this.filebarchoosed.id}/off`
        );
      } else {
        const res = await this.http.post(
          `textfile/${this.filebarchoosed.id}/off`
        );
      }
      this.getFileData(this.curfileInfo);
    },
    showContextmenu(e) {
      const HomeContextMenu = this.$el.parentNode.childNodes[0];
      HomeContextMenu.style.display = "none";
      const contextMenu = this.$refs.contextmenu.$el;
      contextMenu.style.left = `${e.layerX}px`; // 菜单的横坐标位置
      contextMenu.style.top = `${e.layerY}px`; // 菜单的纵坐标位置
      contextMenu.style.display = "block"; // 显示菜单
      this.ClickClearMenu = document.defaultView.addEventListener(
        "click",
        (e) => {
          if (contextMenu.contains(e.target)) {
            document.defaultView.removeEventListener(
              "click",
              this.ClickClearMenu
            );
          }
          contextMenu.style.display = "none"; // 显示菜单
        }
      );
    },
    async getFileData(curfileInfo) {
      this.filebarchoosed = null;
      this.filebarArr = [];
      let id = 1;
      if (curfileInfo !== null) {
        id = curfileInfo.id;
      }
      const res = await this.http.get(`/document/${id}/docinfo`);
      this.filetextArr = res.data.res.fileContainInfo;
      if (this.filetextArr && this.filetextArr.length > 0) {
        this.filebarArr = this.filetextArr.map((item) => {
          const str = item.createdAt;
          const date = new Date(str);
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          const formattedDate = `${year}-${month
            .toString()
            .padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
          const newItem = {
            ...item,
            createTime: formattedDate,
            Renameing: false,
            name: item.filename,
            size: "0kb",
            kind: "txt文件",
            src: "http://localhost:5001/" + item.iconUrl,
          };
          this.$set(item, newItem);
          return newItem;
        });
      }
      this.curPath = await this.http.post(`/document/path/${id}`);
      this.curPathArr = [];
      for (let i = 0; i < this.curPath.data.res.length; i++) {
        this.curPathArr.push({
          id: this.curPath.data.res[i].fatherId,
          fatherName: this.curPath.data.res[i].fatherName,
          fileKind: this.curPath.data.res[i].fileKind,
        });
      }
      this.curfileInfo = res.data.res;
      this.curPathArr.reverse();
      if (this.curfileInfo.id != 1) {
        this.curPathArr.push({
          id: this.curfileInfo.fatherId,
          fatherName: this.curfileInfo.docName,
          fileKind: this.curfileInfo.fileKind,
        });
      }
      localStorage.setItem("curfileInfo", JSON.stringify(this.curfileInfo));
      await Promise.all(
        res.data.res.docContain.map(async (item, index) => {
          const data = await this.http.get(`document/${item}/docinfo`);
          if (data.data.res != null) {
            const str = data.data.res.createdAt;
            const date = new Date(str);
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const formattedDate = `${year}-${month
              .toString()
              .padStart(2, "0")}-${day.toString().padStart(2, "0")}`;
            this.filebarArr.unshift({
              id: data.data.res.id,
              icon: "",
              name: data.data.res.docName,
              size: "567kb",
              kind: "HTML文件",
              createTime: formattedDate,
              createAt: data.data.res.createAt,
              Renameing: false,
              index: index,
              src: "http://localhost:5001/" + data.data.res.iconUrl,
            });
          }
        })
      );
      this.filebarArr.sort((a, b) => a.index - b.index);
      this.isRenameing = false;
      this.onInit();
    },
    async fileOpen(fileinfo) {
      if (fileinfo.iconUrl != "txt.png") {
        // 打开文件
        let preFileInfo = { ...fileinfo };
        this.curfileInfo = fileinfo;
        localStorage.setItem("curfileInfo", JSON.stringify(this.curfileInfo));
        await this.getFileData(this.curfileInfo, preFileInfo);
      } else {
        this.store.dispatch("SetTextInfo", fileinfo);
        this.bus.$emit("opentxtfile", fileinfo);
      }
    },
    async renameItem() {
      if (this.isRenameing) {
        return;
      }
      this.isRenameing = true;

      if (this.filebarchoosed.iconUrl != "txt.png") {
        const data = {
          docName: this.$refs.input[0].value,
        };
        const res = await this.http.post(
          `/document/${this.filebarchoosed.id}/rename`,
          data
        );
      } else {
        const data = {
          filename: this.$refs.input[0].value,
        };
        const res = await this.http.post(
          `/textfile/${this.filebarchoosed.id}/rename`,
          data
        );
      }

      this.getFileData(this.curfileInfo);
    },
    fileSort(type) {
      switch (type) {
        case 0:
          //根据文件名排序
          this.filebarArr.sort((a, b) => a.name?.localeCompare(b.name));
          break;
        case 1:
          // 根据创建时间排序
          this.filebarArr.sort((a, b) => a.createAt?.localeCompare(b.createAt));
          break;
        case 2:
          // 根据大小排序
          this.filebarArr.sort((a, b) => {});
          break;
        case 3:
          break;
        case 4:
          break;
        case 5:
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.content {
  height: 100%;
  width: 100%;
  display: flex;
  .diskmenu {
    flex: 3;
    background: linear-gradient(#e4c8e5, #d0c8e5);
    .top {
      height: 10%;
      width: 100%;
      position: relative;
    }
    .bottom {
      height: 70%;
      display: flex;
      flex-direction: column;
      .item {
        display: flex;
        flex-direction: column;
        padding-left: 0.8rem;
        .text {
          font-size: 0.9rem;
          border-radius: 0.1rem;
          height: 2rem;
          line-height: 2rem;
          margin-right: 20px;
          display: flex;
          img {
            margin: 0 7px 0 3px;
            height: 1rem;
            width: 1rem;
            position: relative;
            top: 0.5rem;
          }
          .bot {
            width: 0.7rem;
            height: 0.7rem;
            border-radius: 50%;
            position: relative;
            top: 10px;
          }
          .bot:nth-child(1) {
            background-color: rgb(246, 45, 55);
          }
          .bot:nth-child(2) {
            background-color: rgb(237, 118, 2);
          }
          .bot:nth-child(3) {
            background-color: rgb(230, 178, 3);
          }
          .bot:nth-child(4) {
            background-color: rgb(31, 168, 48);
          }
          .bot:nth-child(5) {
            background-color: rgb(0, 108, 253);
          }
          .bot:nth-child(6) {
            background-color: rgb(160, 64, 211);
          }

          .bot:nth-child(7) {
            background-color: rgb(115, 103, 117);
          }
          .text {
            margin-left: 0.8rem;
          }
        }

        .text:nth-child(1) {
          font-size: 0.7rem;
          color: rgb(167, 149, 165);
        }

        .active {
          background: rgb(209, 190, 209);
        }
      }
    }
  }

  .maincontent {
    user-select: none;
    flex: 7;
    background: #fff;
    display: flex;
    flex-direction: column;
    .top {
      flex: 2;
      background-color: rgb(247, 243, 249);
      display: flex;
      align-items: center;
      .left {
        display: flex;
      }
    }
    .center {
      flex: 18;
      background-color: #fff;
      border-top: 0.5px rgb(221, 221, 221) solid;
      border-bottom: 0.5px rgb(221, 221, 221) solid;
      display: flex;
      .left {
        flex: 7;
        border-right: 0.5px rgb(221, 221, 221) solid;
        display: flex;
        flex-direction: column;
        .head {
          flex: 1;
          border-bottom: 0.5px rgb(221, 221, 221) solid;
          display: flex;
          align-items: center;
          .temp {
            display: flex;
            height: 80%;
            width: 100%;
            color: rgb(132, 132, 132);
            font-size: 0.8rem;
            .name {
              flex: 5;
              margin-left: 10%;
              border-right: 0.5px rgb(221, 221, 221) solid;
            }
            .memorysize {
              margin-left: 3%;
              flex: 3;
              border-right: 0.5px rgb(221, 221, 221) solid;
            }
            .catagory {
              margin-left: 3%;
              flex: 3;
              border-right: 0.5px rgb(221, 221, 221) solid;
            }
            .createdate {
              margin-left: 3%;
              flex: 5;
            }
          }
        }

        .filecontain {
          flex: 19;
          display: flex;
          flex-direction: column;
          .filebar {
            height: 1.5rem;
            line-height: 1.5rem;
            padding: 0 10px 0 10px;
            margin: 0px 5px 0 5px;
            border-radius: 0.3rem;
            display: flex;
            font-size: 0.8rem;
            input {
              border-color: rgb(42, 98, 217);
            }
            .filename {
              margin-left: 5%;
              flex: 5;
              display: flex;
              img {
                margin: 0 3px 0 3px;
                height: 1.2rem;
                width: 1.2rem;
              }
            }
            .memorysize {
              margin-left: 3%;
              flex: 3;
            }
            .filelkind {
              margin-left: 5%;
              flex: 3;
            }
            .createtime {
              flex: 5;
            }
          }
          .filebar:nth-child(odd) {
            background-color: #fff;
          }
          .filebar:nth-child(even) {
            background-color: rgb(244, 245, 245);
          }
          .active {
            background-color: rgb(42, 98, 217) !important;
          }
        }
      }
      .right {
        flex: 3;
      }
    }
    .bottom {
      flex: 1;
      background-color: #fff;
      font-size: 0.8rem;
      display: flex;
      align-items: center;
      .path {
        height: 70%;
        padding: 0 10px 0 10px;
        display: flex;
        align-items: center;
        color: rgb(149, 149, 149);
        // background-color: red;
        .item {
          img {
            margin: 0 3px 0 3px;
            height: 0.8rem;
            width: 0.8rem;
          }
          span {
            margin: 0 3px 0 0;
          }
        }
      }
    }
  }
}
</style>
